/**
 * 合同列表
 */
var processPersons = {};
var spaces = {};
var dataList = {};

$(document).ready(function(e) {	
	initialSpace();
	search(1);
	$("#btn-search").click(function(){
		search(1);
	});
	$("#btnViewCancle").click(closeDetail);
	initialSalesPerson();
})
/*初始化选项*/

function closeDetail(){
	$("DIV[name='contractList']").show();
	$("DIV[name='viewInfo']").hide();	
}

function initialSalesPerson(){
	
	var requestJson = {functionId:'1120'};
	$.ajax({
        url: '/euc/user/functionusers',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var processPersonSelect = $("#searchUser");
        	$.each(result,function(i,data){
        		$('<option value="'+ data.id +'">'+ data.name +'</option>').appendTo($(processPersonSelect));
        		processPersons[data.id] = data;
			});
        	$(processPersonSelect).val(0).trigger('change');
        },
        error: function () {
        	console.log("/euc/user/functionusers error");
        }  
    });
	
}


function getSearchParameter(currentPage){
	try{
		var clientName = $.trim($("#clientName2").val());		
		if(clientName == ''){
			clientName = $.trim($("#searchUserName").val());
		}
		var spaceId = $("#searchSpace").val();
		if(spaceId == '0'){
			spaceId = '';
		}
		var contractType = $("#searchType").val();
		if(contractType == '0'){
			contractType = '';
		}else{
			contractType = $("#searchType").find("option[value='"+contractType+"']").text();
		}
		var salesPerson = $("#searchUser").val();
		if(salesPerson == '0'){
			salesPerson = '';
		}		
		var beginTime = $("#searchBeginTime").val();
		var endTime = $("#searchEndTime").val();
		var requestJson = {"currentPage":currentPage,"data":{"clientName":clientName,"spaceId":spaceId,"contractType":contractType,"salesPerson":salesPerson,"beginTime":beginTime,"endTime":endTime}};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
}

function detail(id){
	$("DIV[name='contractList']").hide();
	$("DIV[name='viewInfo']").show();	
	var data  = dataList[id];
	var contractType = $.trim(data["contractType"]);
	$("#infoTitle").html($.trim(data["contractType"]));
	
	var productTable = $("#ViewInfo1");
	
	$(productTable).empty();
	if(contractType == "退租合同"){
		$("#contract_list01").hide();
	}else{
		$("#contract_list01").show();
		$.each(data.contractProductList,function(index,contractProduct){
			var htmlProduct = '<tr>';
			htmlProduct +='<td>工位</td>';
			htmlProduct +='<td>'+ $.trim(contractProduct["roomName"])+'</td>';
			htmlProduct +='<td>'+ $.trim(contractProduct["roomPrice"])+'</td>';
			htmlProduct +='<td>'+ $.trim(contractProduct["rentStart"])+'</td>';
			htmlProduct +='<td>'+ $.trim(contractProduct["rentEnd"])+'</td>';
			htmlProduct +='</tr>';
	     	$(productTable).append(htmlProduct);
		});
	}
	
	

	$("#ViewInfo2").empty();
	var htmlA = '<li><label style="width:150px;">承租方(甲方)：</label><label>'+$.trim(data["partyAName"])+'</label></li>';
	htmlA +='<li><label style="width:150px;">地址：</label><label>'+$.trim(data["partyAAddress"])+'</label></li>';
	htmlA +='<li><label style="width:150px;">联系人：</label><label>'+$.trim(data["partyAContact"])+'</label></li>';
	htmlA +='<li><label style="width:150px;">电话：</label><label>'+$.trim(data["partyAContactNumber"])+'</label></li>';
	htmlA +='<li><label style="width:150px;">邮箱：</label><label>'+$.trim(data["partyAEmail"])+'</label></li>';
	$("#ViewInfo2").html(htmlA);
	
	
	$("#ViewInfo3").empty();
	var htmlB = '<li><label style="width:150px;">承租方(乙方)：</label><label>'+$.trim(data["partyBName"])+'</label></li>';
	htmlB +='<li><label style="width:150px;">地址：</label><label>'+$.trim(data["partyBAddress"])+'</label></li>';
	htmlB +='<li><label style="width:150px;">联系人：</label><label>'+$.trim(data["partyBContact"])+'</label></li>';
	htmlB +='<li><label style="width:150px;">电话：</label><label>'+$.trim(data["partyBContactNumber"])+'</label></li>';
	htmlB +='<li><label style="width:150px;">邮箱：</label><label>'+$.trim(data["partyBEmail"])+'</label></li>';
	$("#ViewInfo3").html(htmlB);

	$("#ViewInfo4").empty();
	
	
	var htmlSpace = '<li><label style="width:150px;">所在空间：</label><label>'+$.trim(spaces[data["spaceId"]].spaceName)+'</label></li>';
	htmlSpace +='<li><label style="width:150px;">空间地址：</label><label>'+$.trim(spaces[data["spaceId"]].address)+'</label></li>';
	htmlSpace +='<li><label style="width:150px;">合同编号：</label><label>'+$.trim(data["contractNumber"])+'</label></li>';
	htmlSpace +='<li><label style="width:150px;">签署日期：</label><label>'+$.trim(data["contractTime"])+'</label></li>';
	
	if(contractType == "退租合同"){
		htmlSpace +='<li><label style="width:150px;">退租日期：</label><label>'+$.trim(data["leaveTime"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">退服务费总额：</label><label>'+$.trim(data["backAmount"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">退租押金总额：</label><label>'+$.trim(data["depositAmount"])+'</label></li>';
	}else{
		htmlSpace +='<li><label style="width:150px;">分期方式：</label><label>'+$.trim(data["paymentCount"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">付款方式：</label><label>'+""+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">首付款日期：</label><label>'+$.trim(data["paymentFirstTime"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">首付款金额：</label><label>'+$.trim(data["paymentFirst"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">免租期：</label><label style="width: 200px;">'+$.trim(data["freeTimeStart"]) + "&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;&nbsp;"  + $.trim(data["freeTimeEnd"]) +'</label></li>';
		htmlSpace +='<li><label style="width:150px;">押金总额：</label><label>'+$.trim(data["depositAmount"])+'</label></li>';
		htmlSpace +='<li><label style="width:150px;">最大容纳人数：</label><label>'+""+'</label></li>';
	}
	htmlSpace +='<li><label style="width:150px;">备注：</label><label>'+""+'</label></li>';
	htmlSpace +='<li><label style="width:150px;">服务费总额：</label><label>'+$.trim(data["contractAmount"])+'</label></li>';
	htmlSpace +='<li><label style="width:150px;">房间总数：</label><label>'+$.trim(data["roomCount"])+'</label></li>';
	
	htmlSpace +='<li><label style="width:150px;">合同附件:</label><label>';
	if($.trim(data["filePath"]) != ''){
		htmlSpace +='<a id="reviewPDF" href="'+ $.trim(data["filePath"]) +'"  target="_blank" >预览</a>';
	}
	htmlSpace += '</label></li>';
	
	$("#ViewInfo4").html(htmlSpace);
}

function search(currentPage){

	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	console.log(JSON.stringify(requestJson));
	$.ajax({
        url: '/euc/contract/finance/contracts',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		var spaceName = '';
        		if($.trim(data["spaceId"]) != ''){
        			spaceName =$.trim(spaces[data["spaceId"]].spaceName);
        		}


        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + $.trim(data["clientName"]) + '</td>';
        		html += '<td>' + spaceName + '</td>';
        		html += '<td>' + $.trim(data["contractType"]) + '</td>';
        		html += '<td>' + $.trim(data["contractStartTime"]) + '</td>';
        		html += '<td>' + $.trim(data["contractEndTime"]) + '</td>';
        		html += '<td>' + $.trim(data["roomCount"]) + '</td>';
        		html += '<td>' + $.trim(data["contractAmount"]) + '</td>';
        		if(data["salesPerson"] == null){
        			html += '<td>-</td>';
        		}else{
        			html += '<td>' + $.trim(data["salesPerson"].name) + '</td>';
        		}
        		
        		html += '<td>' + $.trim(data["createUser"].name) + '</td>';
        		html += '<td>' + $.trim(data["createTime"]) + '</td>';  
              	html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">详情</a></td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

/*空间名称*/
function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	var spaceSelect = $("#searchSpace");	

	$.each(spaces,function(key,space){	
		//if(space.id ==1){
			//$('<option value="'+ space.id +'" selected>'+ space.spaceName +'</option>').appendTo($(spaceSelect));
		//}else{
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
		//}
	});
	
}